package pcp

import (
	"encoding/base64"

	"gitee.com/teval/uts"
	"github.com/forgoer/openssl"
)

func AesECBEncrypt(value, key string, pad ...string) (string, error) {
	var p = openssl.PKCS5_PADDING
	if len(pad) > 0 {
		p = uts.Nvl(pad[0], p)
	}
	a := NewAesECBCrypt(key, p)
	return a.Encrypt([]byte(value))
}

func AesECBDecrypt(value, key string, pad ...string) (string, error) {
	var p = openssl.PKCS5_PADDING
	if len(pad) > 0 {
		p = uts.Nvl(pad[0], p)
	}
	a := NewAesECBCrypt(key, p)
	return a.Decrypt(value)
}

func NewAesECBCrypt(key string, pad ...string) (crypt *AesECBCrypt) {
	crypt = &AesECBCrypt{
		Key:     []byte(key),
		Padding: openssl.PKCS5_PADDING,
	}

	if len(pad) > 0 {
		crypt.Padding = pad[0]
	}

	return
}

type AesECBCrypt struct {
	Key     []byte
	Padding string
}

func (a *AesECBCrypt) Encrypt(src []byte) (rst string, err error) {
	dst, err := openssl.AesECBEncrypt(src, a.Key, a.Padding)
	if err != nil {
		return
	}
	rst = base64.StdEncoding.EncodeToString(dst)
	return
}

func (a *AesECBCrypt) Decrypt(data string) (rst string, err error) {
	src, err := base64.StdEncoding.DecodeString(data)
	if err != nil {
		return
	}
	dst, err := openssl.AesECBDecrypt(src, a.Key, a.Padding)
	if err != nil {
		return
	}
	rst = string(dst)
	return
}
